#!/usr/local/bin/python3
# -*- coding: UTF-8 -*-
"""
@author:apple
@file:demo01.py
@time:2022/03/14
"""
import json

import requests
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
import base64


headers = {
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.109 Safari/537.36"
    }

# 如果text不足16位的倍数就用空格补足为16位
def add_to_16(text):
    if len(text.encode('utf-8')) % 16:
        add = 16 - (len(text.encode('utf-8')) % 16)
    else:
        add = 0
    text = text + (chr(add) * add)
    return text.encode('utf-8')

def to_16(data):
    pad = 16-len(data)%16
    data +=chr(pad) * pad
    return data

# 加密函数
def encrypt(text, key , iv):
    key = key.encode('utf-8')
    mode = AES.MODE_CBC
    iv = iv.encode("utf-8")
    # text = to_16(text).encode('utf-8')
    text = add_to_16(text)
    cryptos = AES.new(key, mode, iv)
    cipher_text = cryptos.encrypt(text)
    # 因为AES加密后的字符串不一定是ascii字符集的，输出保存可能存在问题，所以这里转为16进制字符串
    return base64.b64encode(cipher_text)



# 解密后，去掉补足的空格用strip() 去掉
def decrypt(text):
    key = '9999999999999999'.encode('utf-8')
    iv = b'qqqqqqqqqqqqqqqq'
    mode = AES.MODE_CBC
    cryptos = AES.new(key, mode, iv)
    plain_text = cryptos.decrypt(a2b_hex(text))
    return bytes.decode(plain_text).rstrip('\0')


def test01():
    ...
    # print(encrypt("1234"))


def test02():
    ...
    text ='{\"csrf_token\":\"\"}'

    params = {
        "rid":"R_SO_4_191248",
         "threadId":"R_SO_4_191248",
        "pageNo":"1",
        "pageSize":"20",
        "cursor":"-1",
        "offset":"0",
        "orderType":"1",
        "csrf_token":""
    }

    i = "oXfcRGSkYWl1ledi"
    g = "0CoJUm6Qyw8W8jud"
    #f = "00e0b509f6259df8642dbc35662901477df22677ec152b5ff68ace615bb7b725152b3ab17a876aea8a5aa76d2e417629ec4ee341f56135fccf695280104e0312ecbda92557c93870114af6c9d05c4f7f0c3685b7a46bee255932575cce10b424d813cfe4875d3e82047b97ddef52741d546b8e289dc6935b3ece0462db0a22b8e7"
    # encrypt()
    iv = "0102030405060708"

    # eHhjXckqrtZkqcwCalCMx0QuU6Lj9L7Wxouw1iMCnB4=
    text = json.dumps(params)
    enc_str = encrypt(text,key=g,iv=iv).decode("utf-8")
    print(enc_str)
    # eHhjXckqrtZkqcwCalCMx0QuU6Lj9L7Wxouw1iMCnB4=
    params = encrypt(enc_str,key=i,iv=iv)
    encryKey = "d995102104422dbd22013c4b426135ffbaf347a75fb1cb147b60fa751a6570d06f96cdcb5e327683232390f918a64b1697a31bec8b683903da9cc6b70261ace409311fe36c5c8c5d61da1be635d746adbf824e6f270fee0024a4b6fe33e2dec7d04b8496ddb2ed2a722218e1b3194845667edb9ab5a59e3e6432ba38b3af2e36"

    datas = {
        "params": params,
        "encSecKey":encryKey
    }

    response = requests.post("https://music.163.com/weapi/comment/resource/comments/get?csrf_token=",data=datas,headers=headers)
    print(response.text)


if __name__ == '__main__':
    pass
    test02()